<?php
!defined ('P_W') && exit('Forbidden');

class PW_HouseFieldsService {

	var $conf;
	var $field;
	
	function PW_HouseFields() {
		$this->__construct();
	}
	
	function __construct() {
		require (R_P . 'mode/house/config/field_config.php');
		include (R_P . 'data/bbscache/house_config.php');
		$this->conf =& $fieldsList;
		$this->field = $house_field;
	}

	function checkIn($key) {
		$flag = false;
		foreach ($this->conf as $k => $v) {
			if (isset($v[$key])) {
				$flag = $k;break;
			}
		}
		return $flag;
	}

	function getFieldType($key, $flag = null) {
		!$flag && $flag = $this->checkIn($key);
		return isset($this->conf[$flag][$key]) ? $this->conf[$flag][$key]['type'] : null;
	}

	function getFieldsByIds($type, $ids) {
		$houseFieldDB = $this->_getHouseFieldsDB();
		return $houseFieldDB->getByIds($type, $ids);
	}

	function getFieldsById($type, $id) {
		$houseFieldDB = $this->_getHouseFieldsDB();
		return $houseFieldDB->getById($type, $id);
	}

	function fieldParamCheck($type, $data, $except = '') {
		if (empty($data['fieldvalue'])) {
			return '选项名称不能为空';
		}
		$houseFieldDB = $this->_getHouseFieldsDB();
		if ($houseFieldDB->getByValue($type, $data['fieldvalue'], $except)) {
			return $data['fieldvalue'] . '已存在';
		}
		return true;
	}
	function addField($data,$type = ''){
		if(empty($data)) return false;
		$fieldType = $this->getFieldType($type);
		$addFiledMethod = 'addHouse'.ucfirst($fieldType);
		$return = $this->$addFiledMethod($data,$type);
		if($return !== true) return $return;
		return true;	
	}
	/**
	 * 增加一条字段记录
	 * example $data = array('type' => '', 'fieldvalue' => '', 'vieworder' => '', 'ifopen' => '')
	 * @param $data array
	 */
	function addHouseField($data,$type) {
		if (($ret = $this->fieldParamCheck($type, $data)) !== true) return $ret;
		$houseFieldDB = $this->_getHouseFieldsDB();
		$data['type'] = $type;
		$data['id'] = $houseFieldDB->getMinId($type);
		$houseFieldDB->add($data);
		return true;
	}

	function editFieldById($type, $id, $data) {
		if (($ret = $this->fieldParamCheck($type, $data, $id)) !== true) return $ret;
		$houseFieldDB = $this->_getHouseFieldsDB();
		$houseFieldDB->updateById($type, $id, $data);
		return true;
	}

	/**
	 * 删除字段记录
	 * @param $ids  array
	 * @param $type string
	 */
	function deleteHouseField($data,$type) {
		if (!$data || !is_array($data)) return false;
		$houseFieldDB = $this->_getHouseFieldsDB();
		$houseFieldDB->deleteByIds($type, $data);
	}
	
	/**
	 * 删除区域记录
	 * @param $ids  array
	 */
	function deleteHouseArea($data,$type = '') {
		if (!$data || !is_array($data)) return false;
		$houseAreaDB = $this->_getHouseAreaDB();
		$houseAreaDB->deleteByIds($data);
	}
	
	function deleteHouseRange($data,$type){
		list($type,$vstart,$vend,$fieldvalue) = $data;
		$this->edit_range($type, $vstart, $vend, $fieldvalue);
	}
	
	function deleteField($data,$type = ''){
		$fieldType = $this->getFieldType($type);
		$deleteFieldMethod = 'deleteHouse'.ucfirst($fieldType);
		return $this->$deleteFieldMethod($data,$type);
	}

	function getAreaById($id) {
		$houseAreaDB = $this->_getHouseAreaDB();
		return $houseAreaDB->getById($id);
	}

	function areaParamCheck($data, $except = '') {
		if (empty($data['code']) || empty($data['name'])) return '区域名称不能为空';
		if (!preg_match('/\d{6,8}/', $data['code'])) return '区域代号格式不对!';
		$houseAreaDB = $this->_getHouseAreaDB();
		if ($houseAreaDB->getByCode($data['code'], $except)) return '区域代码已经存在';
		return true;
	}

	/**
	 * 增加一条区域记录
	 * example $data = array('code' =>, 'name' =>, 'ifopen' =>)
	 * @param  $data = array
	 */
	function addHouseArea($data,$type = '') {
		if (($ret = $this->areaParamCheck($data)) !== true) return $ret;
		$houseAreaDB = $this->_getHouseAreaDB();
		$houseAreaDB->add($data);
		return true;
	}

	function editAreaById($id, $data) {
		if (($ret = $this->areaParamCheck($data, $id)) !== true) return $ret;
		$houseAreaDB = $this->_getHouseAreaDB();
		$houseAreaDB->updateById($id, $data);
		return true;
	}
	
	function editField($data,$ids,$type){
		$fieldType = $this->getFieldType($type);
		$editFieldMethod = 'editHouse'.ucfirst($fieldType);
		$this->$editFieldMethod($data,$ids,$type);
	}
	/**
	 * 修改区域记录
	 * @param $ids array
	 * @param $data array,
	 */
	function editHouseArea($data,$ids,$type = '') {
		if (!$ids) return false;
		$ids = S::isArray($ids) ? $ids :array($ids);
		$houseAreaDB = $this->_getHouseAreaDB();
		$houseAreaDB->updateByIds($ids, $data);
		return true;
	}
	
	/**
	 * 修改字段记录
	 * @param $type string
	 * @param $ids mixed  数组或者是整型
	 * @param $data array
	 */
	function editHouseField($data,$ids,$type) {
		if (!$ids) return false;
		!S::isArray($ids) && $ids = array($ids);
		$houseFieldDB = $this->_getHouseFieldsDB();
		$houseFieldDB->updateByIds($type, $ids, $data);
		return true;
	}
	
	function editHouseRange($data,$ids,$type){
		list($type,$vstart,$vend,$fieldvalue) = $data;
		$this->edit_range($type, $vstart, $vend, $fieldvalue);
	}

	/**
	 * 修改区间取值
	 * @param $type string
	 * @param $vstart array()
	 * @param $vend array()
	 * @param $fieldvalue array()
	 */
	function edit_range($type, $vstart, $vend, $fieldvalue) {
		$insertdb = array();
		$houseVrangeDB = $this->_getHouseVrangeDB();
		$fielddb = $houseVrangeDB->getByType($type);
		$i = 0;
		foreach ($vstart as $key => $value) {
			if (!$value && !$vend[$key]) continue;
			if (!is_numeric($value) && !is_numeric($vend[$key])) continue;
			$vstart[$key] = (int)$value;
			$vend[$key] = (int)$vend[$key];
			if (!$fieldvalue[$key]) {
				if (!$vend[$key]) {
					$fieldvalue[$key] = $value . '以上';
				} elseif (!$value) {
					$fieldvalue[$key] = $vend[$key] . '以下';
				} else {
					$fieldvalue[$key] = $value . '-' . $vend[$key];
				}
			}
			if (isset($fielddb[$i])) {
				if ($value != $fielddb[$i]['vstart'] || $vend[$key] != $fielddb[$i]['vend'] || $fielddb[$i]['vieworder'] != $i || $fieldvalue[$key] != $fielddb[$i]['fieldvalue']) {
					$houseVrangeDB->updateById($type, $fielddb[$i]['id'], array(
						'fieldvalue'=> $fieldvalue[$key],
						'vstart'	=> $value,
						'vend'		=> $vend[$key],
						'vieworder'	=> $i
					));
				}
			} else {
				$insertdb[] = array(
					'type'		=> $type,
					'fieldvalue'=> $fieldvalue[$key],
					'vstart'	=> $value,
					'vend'		=> $vend[$key],
					'vieworder'	=> $i,
					'ifopen'	=> 1
				);
			}
			$i++;
		}
		if ($insertdb) {
			$houseVrangeDB->adds($insertdb);
		}
		if ($i < count($fielddb) && $deldb = array_slice($fielddb, $i)) {
			$ids = array();
			foreach ($deldb as $key => $value) {
				$ids[] = $value['id'];
			}
			$houseVrangeDB->deleteByIds($type, $ids);
		}
		return true;
	}
	
	function addHouseRange($data,$type){
		list($type,$vstart,$vend,$fieldvalue) = $data;
		$this->edit_range($type, $vstart, $vend, $fieldvalue);
		return true;
	}
	
	/**
	 * 取得房产相关字段信息指定类别下所有列表
	 * @type string 字段类型
	 * @return array   返回房产相关字字段指定类别下信息集合
	 */ 
	function getAllFieldListByType($type){
		$fieldType = $this->getFieldType($type);
		$getAllFieldMethod = 'getAll'.ucfirst($fieldType).'List';
		return $this->$getAllFieldMethod($type);		
	}
	
	function getAllAreaList($type = '',$ifopen = 1){
		if($this->field['area']){
			return $this->field['area'];
		}
		$houseAreaDB = $this->_getHouseAreaDB();
		$area = $houseAreaDB->getAllHouseArea($ifopen);
		return $this->_area($area);
	}
	
	function getAllRangeList($type,$ifopen = 1){
		 if($this->field[$type]) return $this->field[$type];
		 $houseVrangeDB = $this->_getHouseVrangeDB();
		 $vrange = $houseVrangeDB->getAllTypeList($type,$ifopen);
		 return $this->_vrange($vrange);
	}
	
	function getAllFieldList($type,$ifopen = 1){
	 	if($this->field[$type])	return $this->field[$type];
		$houseFieldDB = $this->_getHouseFieldsDB();
	    $field =  $houseFieldDB->getAllTypeList($type,$ifopen);
	    return $this->_field($field);
	}
	
	/**
	 * 取得房产相关字段信息列表
	 * @type 	string 字段类型
	 * @page 	int    页码数
	 * @perpage int    页容量
	 * @return array   返回房产相关字字段信息集合
	 */ 
	function getFieldListByType($type,$page,$perpage){
		$fieldType = $this->getFieldType($type);
		$fieldFunction = 'get'.ucfirst($fieldType).'List';
		return $this->$fieldFunction($type,$page,$perpage);
		
	}
	
	/**
	 * 取得房产相关字段信息总数
	 * @type   string  字段类型
	 * @return int   返回房产相关字字段信息总数
	 */ 
	function getCountFieldList($type){
		$fieldType = $this->getFieldType($type);
		$countFunction = 'getCount'.ucfirst($fieldType);
		return $this->$countFunction($type);
		
	}
	/**
	 * 取得区域字段信息列表
	 * @type 	string 字段类型  在区域中无用
	 * @page 	int    页码数
	 * @perpage int    页容量
	 * @return array   返回区域字段信息集合
	 */ 	
	function getAreaList($type,$page,$perpage){
		$houseAreaDB = $this->_getHouseAreaDB();
	    return $houseAreaDB->getAreaList($page,$perpage);
	}
	
	function getCountArea($type){
		$houseAreaDB = $this->_getHouseAreaDB();
		return $houseAreaDB->getCountAreaList();
	}
	
	/**
	 * 取得范围字段信息列表
	 * @type 	string 字段类型
	 * @page 	int    页码数
	 * @perpage int    页容量
	 * @return array   返回范围字段信息集合
	 */ 	
	function getRangeList($type,$page,$perpage){
		 $houseVrangeDB = $this->_getHouseVrangeDB();
		 return $houseVrangeDB->getTypeList($type,$page,$perpage);
	}
	
	function getCountRange($type){
		 $houseVrangeDB = $this->_getHouseVrangeDB();
		 return $houseVrangeDB->getCountTypeList($type);
	}
	
	/**
	 * 取得字段信息列表
	 * @type 	string 字段类型
	 * @page 	int    页码数
	 * @perpage int    页容量
	 * @return array   返回字段信息集合
	 */ 
	function getFieldList($type,$page,$perpage){
		$houseFieldDB = $this->_getHouseFieldsDB();
	    return $houseFieldDB->getTypeList($type,$page,$perpage);
	}
	
	function getCountField($type){
		$houseFieldDB = $this->_getHouseFieldsDB();
	    return $houseFieldDB->getCountTypeList($type);
	}
	
	function getMaxVieworder($type) {
		$houseFieldDB = $this->_getHouseFieldsDB();
	    return $houseFieldDB->getMaxVieworder($type);
	}
	
	function _getHouseFieldsDB(){
		return House::loadDB('HouseFields');
	}
	
	function _getHouseVrangeDB(){
		return House::loadDB('HouseVrange');
	}
	
	function _getHouseAreaDB(){
		return House::loadDB('HouseArea');
	}
	/**
	 * 更新字段信息缓存
	 */
	function updateFieldsCache(){
		$fielddb = array();
		$houseFieldDB = $this->_getHouseFieldsDB();
		$houseAreaDB = $this->_getHouseAreaDB();
		$houseVrangeDB = $this->_getHouseVrangeDB();
		$openFields = $houseFieldDB->getOpenHouseFieldList();
		$openArea = $houseAreaDB->getOpenAreaList();
		$openVrange = $houseVrangeDB->getOpenVrangeFieldList();
		$openFields = S::isArray($openFields) ? $openFields : array();
		$openArea = S::isArray($openArea) ? $openArea : array();
		$openVrange = S::isArray($openVrange) ? $openVrange : array();
		$fielddb['area'] = $this->_area($openArea);
		$field = $this->_field($openFields);
		$vrange =$this-> _vrange($openVrange);
		$fielddb = array_merge($fielddb,$field,$vrange);
		setConfig('house_field', $fielddb, null, true);
		updatecache_conf('house', true);		
	}
	function _area($openArea){
		$openArea = is_array($openArea) ? $openArea : array();
		$area = array();
		foreach ($openArea as $rt) {
			$area[$rt['id']] = array(
				'code'	=> $rt['code'],
				'name'	=> $rt['name']
			);
		}
		return $area;
	}
	function _vrange($openVrange){
		$openVrange = is_array($openVrange) ? $openVrange : array();
		$vrange = array();
		foreach ($openVrange as $rt) {
			$vrange[$rt['type']][$rt['id']] = array(
				'value'	=> $rt['fieldvalue'],
				'start'	=> $rt['vstart'],
				'end'	=> $rt['vend']
			);
		}
		return $vrange;
	}
	function _field($openFields){
		$openFields = is_array($openFields) ? $openFields : array();
		$fields = array();
		foreach ($openFields as $rt) {
			$fields[$rt['type']][$rt['id']] = array(
					'name' => $rt['fieldvalue'],
					'parent' => $rt['parent'],
				);
		}
		return $fields;
	}
	function getCompsiteFieldsByType($type){
		$fieldtype = $this->getFieldType($type);
		$fields = $this->getAllFieldListByType($type);
		$tmpdata = array();
		$fieldvalue = '';
		foreach ($fields as $key=>$value){
			if($fieldtype == 'area'){
				$fieldvalue = $value['name'];
			}elseif($fieldtype == 'range'){
				$fieldvalue = $value['value'];
			}else{
				$fieldvalue = $value['name'];
			}
			$tmpdata[$key]  = $fieldvalue;
		}
		return $tmpdata;
	}
	/*
	 * 根据区域取得商圈
	 */
	function getPlateByAreaId($areaid){
		$areaid = (int)$areaid;
		$plate = $this->getAllFieldListByType('plate');
		$newplate = array();
		foreach($plate as $key=>$value){
			if($areaid && $areaid == $value['parent']) $newplate[$key] = $value['name'];
		}
		return $newplate;
	}
	
	/**
	 * 取得中国省市下的区县
	 *@param string $province  省
	 *@param string $city 市
	 *@param int $page
	 *@perpage int $perpage
	 *@return array 
	 */
	function getAreaOfChina($province = '',$city = '',$page = 1,$perpage = 20){
		$id .= $province ? $province : '';
		$id .= $province && $city ? $city : '';
		(!is_numeric($page) || $page < 1) && $page = 1;
		$content = explode("\n", readover(M_P . 'config/area.txt'));
		$provincedb = $citydb = $list = $areadb = $ids = array();
		$j = 0;
		$len = strlen($id);
		$start = ($page - 1) * $perpage;
		$end = $start + $perpage;
		foreach ($content as $key => $value) {
			$tmp = explode("\t",$value);
			$code = str_split($tmp[0], 2);
			if ($code[1] == '00' && $code[2] == '0') {
				$provincedb[$code[0]] = trim($tmp[1]);
			} elseif ($code[2] == '00') {
				$citydb[$code[0]][$code[1]] = trim($tmp[1]);
			}
			if ((!$id || $len == 2 && $code[0] == $id || $len == 4 && $id == $code[0].$code[1])) {
				if ($j >= $start && $j < $end) {
					$list[$tmp[0]] = trim($tmp[1]);
					$ids[] = $tmp[0];
				}
				++$j;
			}
		}
		if ($ids) {
			$houseAreaDB = $this->_getHouseAreaDB();
			$areaList = $houseAreaDB->getAllAreaListByCode($ids);
			foreach($areaList as $value){
				$areadb[$value['code']] = 1;
			}
		}
		return array($provincedb,$citydb,$areadb,$list,$ids,$j);	
	}
	/**
	 * 导入区域
	 * @param array $codeList
	 */
	function importAreaList($codeList){
		$codeList = is_array($codeList) ? $codeList : array($codeList);
		$insertdb = array();
		$content = explode("\n", readover(M_P . 'config/area.txt'));
		foreach ($content as $key => $value) {
			$tmp = explode("\t",$value);
			if (in_array($tmp[0], $codeList)) {
				$insertdb[] = array($tmp[0], trim($tmp[1]), 1);
			}
		}
		if($insertdb){
			$houseAreaDB = $this->_getHouseAreaDB();
			$houseAreaDB->importAreaList($insertdb);
		}
	}
}
?>